////////////////////////////////////////////////////////////////////////////////
//
//  People2 Creative Systems  
//  Copyright 2008 People2 Creative Systems
//
//	License GPL v2.0
//
////////////////////////////////////////////////////////////////////////////////

package com.people2.commons.autolistener
{
	import flash.utils.describeType;
	
	public class HandlerManager
	{
		public function HandlerManager(enforcer:EnforcerSingleton)
		{
		}	
		private static var _instance:HandlerManager;
		
		public static function get instance():HandlerManager
		{
			if (_instance == null)
				_instance = new HandlerManager(new EnforcerSingleton());
			
			return _instance;
		}
		
		private function loadMetadata(target:*):void
		{
			var clazzXML: XML = flash.utils.describeType(target);
	    trace("classXML -> ",clazzXML);
	    
 			
 			var metadata:XMLList = clazzXML.method.metadata.(@name == "Handler");

 			var lt:int = metadata.length();
 			
 			for (var i:int=0; i < lt; i++)
 			{
 				var methodName:String, eventName:String, targetName:String, priority:String;

		    methodName = metadata[i].parent().@name;
		    eventName = metadata[i].arg.(@key == "event").@value;
		    targetName =  metadata[i].arg.(@key == "target").@value;
		    priority =  metadata[i].arg.(@key == "prior").@value;

		    if (priority == null)
		    	priority = "0";
		    	
 				trace("method -> ",methodName);
		    trace("event -> ",eventName);
		    trace("target -> ",targetName);
		    trace("priority -> ",priority);
		    
		    
		    if (targetName == null)
		    	target.addEventListener(eventName,target,false,Number(priority),true);
		    else
		    	target[targetName].addEventListener(eventName,target[methodName],false,Number(priority),true);
		    
 			}
					
		}
		
		public function autoListeners(target:*):void
		{
			loadMetadata(target);
		}

	}
}
class EnforcerSingleton{}